﻿
using Klear.Views;

namespace Klear.Services;

using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;

 
public static class DialogManage
{
    private static readonly Dictionary<DialogType, Dialog> _dialogBases = new();
    
    public static void Show(DialogType type, string content, int height = 450, int width = 500, int timing = 3000000)
    {
        Dialog dialog;
        lock (_dialogBases)
        {
            if (_dialogBases.Remove(type, out var dialogBase))
            {
                try
                {
                    dialogBase.Close();
                }
                catch
                {
                }
            }
            dialog = new Dialog
            {
                Height = height,
                Width = width,
                WindowStartupLocation = WindowStartupLocation.Manual // 不设置的话无法修改窗口位置
            };
            if (timing > 0)
            {
                _ = Task.Run(async () =>
                {
                    await Task.Delay(timing);
                    if (_dialogBases.Remove(type, out var dialog))
                    {
                        _ = Dispatcher.UIThread.InvokeAsync(() =>
                        {
                            try
                            {
                                dialog.Close();
                            }
                            catch
                            {
                            }
                        });
                    }
                });
            }
            _dialogBases.TryAdd(type, dialog);
        }
        var bounds = dialog.Screens.ScreenFromVisual(dialog).Bounds;
        int centerX = (int)(bounds.Width - dialog.Width) / 2;
        int centerY = (int)(bounds.Height - dialog.Height) / 2;
        dialog.Position = new PixelPoint(centerX, centerY);
        var contentBox = dialog.Find<TextBlock>("Content");
        dialog.Show();
    }
}
 
public enum DialogType
{
    /// <summary>
    /// 左上
    /// </summary>
    topLeft,
 
    /// <summary>
    /// 居中靠上
    /// </summary>
    topCenter,
 
    /// <summary>
    /// 右上
    /// </summary>
    topRight,
 
    /// <summary>
    /// 左下
    /// </summary>
    leftLower,
 
    /// <summary>
    /// 居中靠下
    /// </summary>
    centerLower,
 
    /// <summary>
    /// 右下
    /// </summary>
    rightLower
}